// src/store/index.js
import { createStore } from 'vuex';
import { getWordDetails } from '../services/dictionaryService';

export default createStore({
    state: {
        words: [
            { id: 1, word: 'abandon', definition: 'to leave completely and finally', isLearned: false, phonetic: '', chineseDefinition: '' },
            { id: 2, word: 'example', definition: 'an instance serving as a representation', isLearned: false, phonetic: '', chineseDefinition: '' }
        ]
    },
    mutations: {
        markAsLearned(state, id) {
            const word = state.words.find(w => w.id === id);
            if (word) word.isLearned = true;
        },
        importWords(state, newWords) {
            state.words = newWords;
        },
        updateWordDetails(state, { id, details }) {
            const word = state.words.find(w => w.id === id);
            if (word) {
                // 更新音标
                const phonetics = details[0].phonetics;
                const phonetic = phonetics.find(p => p.text)?.text || '';
                word.phonetic = phonetic;

                // 更新定义
                const meanings = details[0].meanings;
                const definition = meanings[0]?.definitions[0]?.definition || '';
                word.definition = definition;

                // 这里假设你有中文释义的数据源，如果没有可以留空
                word.chineseDefinition = ''; // 你可以在这里添加中文释义的逻辑
            }
        },
        updateWord(state, { id, word }) {
            const index = state.words.findIndex(w => w.id === id);
            if (index !== -1) {
                state.words[index] = { ...state.words[index], ...word };
            }
        }
    },
    actions: {
        importWords({ commit }, file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = (event) => {
                    try {
                        const content = event.target.result;
                        const newWords = JSON.parse(content);
                        commit('importWords', newWords);
                        resolve();
                    } catch (error) {
                        reject(error);
                    }
                };
                reader.onerror = (error) => {
                    reject(error);
                };
                reader.readAsText(file);
            });
        },
        async fetchWordDetails({ commit, state }, wordId) {
            const word = state.words.find(w => w.id === wordId);
            if (word) {
                try {
                    const details = await getWordDetails(word.word);
                    commit('updateWordDetails', { id: wordId, details });
                } catch (error) {
                    console.error('Error fetching word details:', error);
                }
            }
        },
        updateWord({ commit }, { id, word }) {
            commit('updateWord', { id, word });
        }
    },
    modules: {}
});